function ensure_shopname_for_list(callback) {
  frappe.call({
    method: "upsystem.upsystem.api_wdt_stock.get_accessible_usershops",
    callback(r) {
      const message = r.message || {};
      const shops = message.shops || [];

      if (!shops.length) {
        frappe.msgprint(__("当前用户没有可用的 usershop，请先配置店铺"));
        return;
      }

      if (shops.length === 1) {
        callback(shops[0].name);
        return;
      }

      const d = new frappe.ui.Dialog({
        title: __("请选择一个 Shopify 店铺"),
        fields: [
          {
            fieldtype: "Select",
            fieldname: "shopname",
            label: __("Shopify Shop"),
            options: shops.map((s) => s.name).join("\n"),
            reqd: 1,
          },
        ],
        primary_action_label: __("确定"),
        primary_action(values) {
          if (!values.shopname) return;
          callback(values.shopname);
          d.hide();
        },
      });

      d.show();
    },
  });
}

frappe.listview_settings["WDT Shopify Inventory Snapshot Inst"] = {
  onload(listview) {
    // 1) 初始化 Item
    listview.page.add_action_item(__("初始化Item"), () => {
      ensure_shopname_for_list((shopname) => {
        frappe.confirm(
          __("将根据当前用户可访问的所有 Item 初始化快照，可能需要一定时间，确认继续？"),
          () => {
            frappe.call({
              method: "upsystem.upsystem.api_wdt_stock.init_inventory_snapshot",
              args: { shopname },
              freeze: true,
              freeze_message: __("正在初始化 Item 至库存快照..."),
              callback(r) {
                if (!r.message) {
                  frappe.msgprint(__("初始化失败"));
                  return;
                }
                if (r.message.success) {
                  frappe.msgprint(
                    __(
                      `初始化完成，新增 ${r.message.created || 0} 条，更新 ${r.message.updated || 0} 条。`
                    )
                  );
                  listview.refresh();
                } else {
                  frappe.msgprint(r.message.message || __("初始化失败"));
                }
              },
            });
          }
        );
      });
    });

    // 2) 刷新仓库库存（WDT）
    listview.page.add_action_item(__("刷新仓库库存"), () => {
      ensure_shopname_for_list((shopname) => {
        frappe.call({
          method: "upsystem.upsystem.api_wdt_stock.refresh_wdt_stock_snapshot",
          args: { shopname },
          freeze: true,
          freeze_message: __("正在从旺店通刷新库存..."),
          callback(r) {
            if (!r.message) {
              frappe.msgprint(__("刷新失败"));
              return;
            }
            if (r.message.success) {
              frappe.msgprint(
                __(
                  `旺店通库存刷新完成，成功 ${r.message.updated || 0} 条，未命中 ${r.message.missed || 0} 条。`
                )
              );
              listview.refresh();
            } else {
              frappe.msgprint(r.message.message || __("刷新失败"));
            }
          },
        });
      });
    });

    // 3) 刷新 Shopify 库存
    listview.page.add_action_item(__("刷新shopify库存"), () => {
      ensure_shopname_for_list((shopname) => {
        frappe.call({
          method: "upsystem.upsystem.api_wdt_stock.refresh_shopify_stock_snapshot",
          args: { shopname },
          freeze: true,
          freeze_message: __("正在从 Shopify 刷新库存..."),
          callback(r) {
            if (!r.message) {
              frappe.msgprint(__("刷新失败"));
              return;
            }
            if (r.message.success) {
              frappe.msgprint(
                __(
                  `Shopify 库存刷新完成，成功 ${r.message.updated || 0} 条，未命中 ${r.message.missed || 0} 条。`
                )
              );
              listview.refresh();
            } else {
              frappe.msgprint(r.message.message || __("刷新失败"));
            }
          },
        });
      });
    });

    // 4) 回写 Shopify 库存（对勾选记录）
    listview.page.add_action_item(__("回写shopify库存"), () => {
      const selected = listview.get_checked_items();
      if (!selected.length) {
        frappe.msgprint(__("请先在列表中选择至少一条记录"));
        return;
      }

      const names = selected.map((d) => d.name);

      frappe.call({
        method: "upsystem.upsystem.api_wdt_stock.bulk_update_shopify_inventory",
        args: {
          docnames: names,
        },
        freeze: true,
        freeze_message: __("正在批量更新 Shopify 库存..."),
        callback(r) {
          if (!r.message) {
            frappe.msgprint(__("调用失败"));
            return;
          }
          if (r.message.success) {
            frappe.msgprint(
              __(
                `已成功更新 ${r.message.updated || 0} 条，失败 ${r.message.failed || 0} 条。`
              )
            );
            listview.refresh();
          } else {
            frappe.msgprint(r.message.message || __("批量更新失败"));
          }
        },
      });
    });
  },
};

